﻿using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.ObjectMapping;
using Abp.Runtime.Caching;
using AVIS.OutBound.CarGroups;
using AVIS.OutBound.ORFleets.Cache;
using AVIS.OutBound.Regions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AVIS.OutBound.ORFleets
{
    public class ORFleetManager : DomainService, IORFleetManager
    {
        private readonly IRepository<ORFleet> _ORFleetRepository;
        private readonly IObjectMapper _objectMapper;
        private readonly ICacheManager _CacheManager;

        public ORFleetManager(IRepository<ORFleet> ORFleetRepository,
            IObjectMapper objectMapper,
            ICacheManager CacheManager)
        {
            _ORFleetRepository = ORFleetRepository;
            _objectMapper = objectMapper;
            _CacheManager = CacheManager;
        }

        /// <summary>
        /// 获取本地数据库中的车辆信息
        /// </summary>
        /// <param name="region">区域</param>
        /// <param name="carGroup">车组</param>
        /// <returns></returns>
        public ORFleet GetORFleet(Region region, CarGroup carGroup)
        {
            var cacheKey = string.Format("{0}_{1}_{2}", region.RegionShortCode, carGroup.ModelCode, carGroup.SIPPCode);
            var cacheItem = _CacheManager.GetORFleetCache().Get(cacheKey,
                f => GetORFleetInDB(region.RegionShortCode, carGroup.ModelCode, carGroup.SIPPCode));
            var fleet = _objectMapper.Map<ORFleet>(cacheItem);
            return fleet;
        }

        public ORFleetCacheItem GetORFleetInDB(string regionShortCode, string ModelCode, string SIPPCode)
        {
            var Fleet = _ORFleetRepository.FirstOrDefault(a => a.RegionCode == regionShortCode && a.CarGroup == ModelCode && a.SIPPCode == SIPPCode);
            var data = _objectMapper.Map<ORFleetCacheItem>(Fleet);
            return data;
        }
    }
}
